//
//  AppDelegate.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/3/28.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import SwiftyJSON
import Alamofire

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        UIApplication.shared.statusBarStyle = .lightContent
        
        window = UIWindow(frame:UIScreen.main.bounds)
        window?.backgroundColor = UIColor.white
        let navcationVC = UINavigationController(rootViewController: LoginViewController())
        
        IQKeyboardManager.sharedManager().enable = true
    IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true
        
        window?.rootViewController = navcationVC
        window?.makeKeyAndVisible()
        configJpush()
        configGaoDe()
        configException()
        return true
    }
    
    //极光配置
    func configJpush() -> Void {
        
//        //通知类型（这里将声音、消息、提醒角标都给加上）
//        let userSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound],
//                                                      categories: nil)
//        if ((UIDevice.current.systemVersion as NSString).floatValue >= 8.0) {
//            //可以添加自定义categories
//            JPUSHService.register(forRemoteNotificationTypes: userSettings.types.rawValue,
//                                  categories: nil)
//        }
//        else {
//            //categories 必须为nil
//            JPUSHService.register(forRemoteNotificationTypes: userSettings.types.rawValue,
//                                  categories: nil)
//        }

        
        if #available(iOS 10.0, *){
            let entiity = JPUSHRegisterEntity()
            entiity.types = Int(UNAuthorizationOptions.alert.rawValue |
                UNAuthorizationOptions.badge.rawValue |
                UNAuthorizationOptions.sound.rawValue)
            JPUSHService.register(forRemoteNotificationConfig: entiity, delegate: self as JPUSHRegisterDelegate)
        } else if #available(iOS 8.0, *) {
            let types = UIUserNotificationType.badge.rawValue |
                UIUserNotificationType.sound.rawValue |
                UIUserNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: types, categories: nil)
        }else {
            let type = UIRemoteNotificationType.badge.rawValue |
                UIRemoteNotificationType.sound.rawValue |
                UIRemoteNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: type, categories: nil)
        }
        
        // 启动JPushSDK
        JPUSHService.setup(withOption: nil, appKey: "f24f118329c5020b4224bb40",
                           channel: nil, apsForProduction: true)
//        JPUSHService.registrationIDCompletionHandler { (resCode, registrationId) in
//            print(resCode)
//        }
    }
    
    //高德配置
    func configGaoDe() -> Void {
        AMapServices.shared().apiKey = "a0fcf126707e745056e5692c03cc20f2"
        
    }
    
    //配置崩溃日志
    func configException() -> Void {
        MyUncaughtExceptionHandler.setDefaultHandler()
        let str = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
        let dataPath = str.appending("/Exception.txt")
        let data = NSData.init(contentsOfFile: dataPath)
        if data != nil {
            sendExceptionLog(data: data! as Data, path: dataPath)
        }
        
    }
    
    //发送崩溃日志
    func sendExceptionLog(data:Data,path:String) -> Void {
        
        //应用程序信息
        let infoDictionary = Bundle.main.infoDictionary!
        //主程序版本号
        let majorVersion = infoDictionary["CFBundleShortVersionString"]
        let appVersion = majorVersion as! String
        //iOS版本
        let iosVersion = UIDevice.current.systemVersion
//        //设备udid
//        let Ludid = UIDevice.current.identifierForVendor?.uuidString
        
        var tokenStr = ""
        if UserDefaults.standard.value(forKey: "Token") != nil {
            tokenStr = UserDefaults.standard.value(forKey: "Token") as! String
        }
        var uploadUrl = ""
        if (tokenStr != "") {
            
           uploadUrl = uploadErrorUrl + "?token=" + tokenStr + "&version=" + iosVersion + "&majorVersion=" + appVersion
            
        }else {
           uploadUrl = uploadErrorUrl + "?token=" + "" + "&version=" + iosVersion + "&majorVersion=" + appVersion
        }
        
        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(data, withName: "filed", fileName:"iosException.txt", mimeType: "image/jpeg")
        }, to: uploadUrl) { (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseString { response in
                    
                    switch response.result.isSuccess {
                    case true:
                        var basemodel = DefaultData()
                        basemodel = DefaultData.deserialize(from: response.value)!
                        
                        switch basemodel.status! {
                        case true:
                            let fileManger = FileManager.default

                            try! fileManger.removeItem(atPath:path)
                            print("上传成功")
                        case false:
                            print("上传失败")
                        }
                    case false:
                        print(response.result.error!)
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    }
    
    //融云配置
    func configRongCloud() -> Void {
//    RCIM.shared().initWithAppKey("m7ua80gbmpwkm")
//        RCIM.shared().connectionStatusDelegate = self as! RCIMConnectionStatusDelegate
//        RCIM.shared().userInfoDataSource = self as! RCIMUserInfoDataSource
//        RCIM.shared().receiveMessageDelegate = self as! RCIMReceiveMessageDelegate
//        RCIM.shared().groupInfoDataSource = self as! RCIMGroupInfoDataSource
//
//        // 设置全局的属性
//        RCIM.shared().globalMessageAvatarStyle = RCUserAvatarStyle.USER_AVATAR_CYCLE
//        RCIM.shared().globalConversationAvatarStyle = RCUserAvatarStyle.USER_AVATAR_CYCLE
//        RCIM.shared().globalMessagePortraitSize = CGSize.init(width: 50, height: 50)
//        RCIM.shared().globalConversationPortraitSize = CGSize.init(width: 50, height: 50)
//        RCIM.shared().globalNavigationBarTintColor = BaseColor.NavColor
    }

    
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    UIApplication.shared.applicationIconBadgeNumber = 0
        JPUSHService.setBadge(0)
    }

    func applicationWillEnterForeground(_ application: UIApplication) {

    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        //注册 DeviceToken
        JPUSHService.registerDeviceToken(deviceToken)
    }
    
    func application(_ application: UIApplication,
                     didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                     fetchCompletionHandler
        completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
    }
    
    func application(_ application: UIApplication,
                     didFailToRegisterForRemoteNotificationsWithError error: Error) {
        //可选
        NSLog("did Fail To Register For Remote Notifications With Error: \(error)")
    }


}

extension AppDelegate: JPUSHRegisterDelegate{
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        
    }
    
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        print(">JPUSHRegisterDelegate jpushNotificationCenter willPresent");
        let userInfo = notification.request.content.userInfo
        if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
        }
//        completionHandler(Int(UNAuthorizationOptions.alert.rawValue))// 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
        completionHandler(Int(UNAuthorizationOptions.alert.rawValue))
//播放声音
        
        let str = getJSONStringFromDictionary(dictionary: userInfo as NSDictionary) as String

        var jmodel = JPushModel()
        jmodel = JPushModel.deserialize(from:str)!
        if ((jmodel.aps?.alert) != nil) {
    SpeechUtteranceManager.shared.speechWeather(with: (jmodel.aps?.alert)!)
        }
  }
    
  func getJSONStringFromDictionary(dictionary:NSDictionary) -> NSString {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
    let data : NSData! = try! JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString!
    }
    
}

